/*
 * Copyright 2017-2101 Innel.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.hykj.xxltest.controller;

import com.github.pagehelper.PageInfo;
import com.hykj.xxltest.base.AppBack;
import com.hykj.xxltest.base.NumberHelper;
import com.hykj.xxltest.base.RequiresRole;
import com.hykj.xxltest.model.*;
import com.hykj.xxltest.service.*;
import com.hykj.xxltest.utils.ExcelReader;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author innel
 * @date 2018-07-04 14:27:49
 */
@Controller
@RequestMapping("/courierorder")
@Api(description = "")
public class CourierorderController {

    private static final Logger logger = Logger.getLogger(CourierorderController.class);

    @Autowired
    private CourierorderService courierorderService;

    @Autowired
    private CourierService courierService;

    @Autowired
    public UserVerifyService userVerifyService;

    @Autowired
    private OrderpicService orderpicService;

    @Autowired
    private UserService userService;


    /**
     * 列表
     */
    @RequestMapping("/list")
    @ResponseBody
//    @RequiresRole(role = "1")
    @ApiOperation(
            value = "获取列表",
            notes = "备注：",
            response = CourierorderModel.class,
            httpMethod = "POST")
    public AppBack list(@ApiParam(value = "每页显示个数,不填默认10")
                        @RequestParam(required = false)
                                Integer pageSize,
                        @ApiParam(value = "用户ID")
                        @RequestParam(required = false)
                                Integer userid,
                        @ApiParam(value = "工人id")
                            @RequestParam(required = false)
                                    Integer courierid,
                        @ApiParam(value = "宝贝数量")
                        @RequestParam(required = false)
                                Integer goodnum,
                        @ApiParam(value = "0 未支付 1 微信 2 余额 3 线下")
                        @RequestParam(required = false)
                                Integer paytype,
                        @ApiParam(value = "1 = 安装 2= 维修")
                        @RequestParam(required = false)
                                Integer ordertype,
                        @ApiParam(value = "订单状态 -1 =已删除 0 = 待分配 1=已分配待确认 2 已确认待完成 3=已完成")
                        @RequestParam(required = false)
                                Integer status,
                        @ApiParam(value = "开始时间 范例 2017-11-06 16:02:11", hidden = true)
                        @RequestParam(required = false)
                                String startTime,
                        @ApiParam(value = "截止时间 格式 YYYYMMDD 也可以", hidden = true)
                        @RequestParam(required = false)
                                String endTime,
                        @ApiParam(value = "搜索关键字")
                        @RequestParam(required = false)
                                String searchKey,
                        @ApiParam(value = "是否是后台列表请求", hidden = true)
                        @RequestParam(required = false)
                                String backList,
                        @ApiParam(value = "是否简单显示", hidden = true)
                        @RequestParam(required = false)
                                String noD,
                        @ApiParam(value = "不填不分页")
                        @RequestParam(required = false)
                                Integer page) {
        Map<String, Object> params = new HashMap<>();
        params.put("pageSize", pageSize);
        params.put("userid", userid);
        params.put("goodnum", goodnum);
        params.put("paytype", paytype);
        params.put("ordertype", ordertype);
        params.put("status", status);
        params.put("startTime", startTime);
        params.put("endTime", endTime);
        params.put("searchKey", searchKey);
        params.put("noD", noD);
        params.put("backList", backList);
        params.put("status", status);
        params.put("courierid",courierid);
        if (page == null) {
            return new AppBack(courierorderService.getDList(params));
        }
        PageInfo<CourierorderModel> p = courierorderService.getDList(params, page);
        return new AppBack(p);
    }

    /**
     * 分配工人
     */
    @RequestMapping("/setCourier")
    @ResponseBody
    @RequiresRole(role = "1")
    @ApiOperation(
            value = "后台专用",
            httpMethod = "POST"
    )
    public AppBack setCourier(Integer courierid, Integer courierorderid) {
        CourierorderModel courierorder = courierorderService.getByIdD(courierorderid);
        if (courierid == null || courierorderid == null) {
            return new AppBack(-2, "必填信息不能为空");
        }
        if (courierorder == null) {
            return new AppBack(-1, "当前资源不存在");
        }
        courierorder.setCourierid(courierid);
        courierorder.setFpTime(new Date());
        courierorder.setStatus(1);
        courierorderService.update(courierorder);
        CourierModel courierModel = courierService.getById(courierid);
        //发送验证码
        String code=(int) (Math.random()*9000+1000)+"";
        UserVerifyModel userVerify = new UserVerifyModel();
        userVerify.setStatus(0);
        userVerify.setPhone(courierModel.getPhone());
        userVerifyService.sendSDK(courierModel.getPhone(),"","1","","");
        userVerifyService.create(userVerify);
        UserModel userModel = userService.getById(courierorder.getUserid());
        if (userModel != null){
            userVerify.setPhone(userModel.getPhone());
            userVerifyService.sendSDK(userModel.getPhone(),code,"2",courierModel.getNickname(),courierModel.getPhone());
            userVerifyService.create(userVerify);
        }




        return new AppBack();
    }

    /**
     * 信息
     */
    @RequestMapping("/info")
    @ResponseBody
    @RequiresRole(role = "1")
    @ApiOperation(
            value = "获取",
            notes = "备注：",
            response = CourierorderModel.class,
            httpMethod = "POST")
    public AppBack info(
            @ApiParam(value = "的ID", required = true)
            @RequestParam Integer courierorderId) {
        CourierorderModel courierorder = courierorderService.getByIdD(courierorderId);
        if (courierorder == null) {
            return new AppBack(-1, "当前资源不存在");
        }
        return new AppBack(courierorder);
    }

    /**
     * 订单导入
     */
    @RequestMapping("/excelDl")
    @ResponseBody
    @RequiresRole(role = "1")
    @ApiOperation(
            value = "后台专用",
            httpMethod = "POST"
    )
    public AppBack excelDl(String excelPath) throws FileNotFoundException {

        ExcelReader excelReader = new ExcelReader();
//        InputStream is2 = new FileInputStream("e:\\q.xls");
        InputStream is3 = new FileInputStream("D:\\upload\\image\\" + excelPath);
        Map<Integer, List<String>> map = excelReader.readExcelContent(is3);
        for (int i = 1; i <= map.size(); i++) {
            CourierorderModel courierorderModel = new CourierorderModel();
            List<String> list = map.get(i);
            courierorderModel.setUsername(list.get(0));
            courierorderModel.setUsermemo(list.get(1));
            courierorderModel.setLinkname(list.get(2));
            courierorderModel.setLinkaddress(list.get(3));
            courierorderModel.setLinkphone(list.get(4));
            courierorderModel.setOrdermemo(list.get(5));
            if (NumberHelper.isNumericFloat(list.get(6))) {
                BigDecimal flag = new BigDecimal(list.get(6));
                courierorderModel.setGoodnum(flag);


            }
            courierorderModel.setNewaddress(list.get(7));
            courierorderModel.setStatus(0);
            courierorderModel.setOrdertype(1);
            courierorderModel.setPaytype(1);
            courierorderModel.setCourierid(0);


            courierorderService.create(courierorderModel);
        }

        return new AppBack();
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @ResponseBody
    @RequiresRole(role = "1")
    @ApiOperation(
            value = "保存",
            notes = "备注：",
            httpMethod = "POST")
    public AppBack save(
            @ApiParam(value = "用户ID", required = true)
            @RequestParam
                    Integer userid,


            @ApiParam(value = "买家会员名", required = true)
            @RequestParam
                    String username,


            @ApiParam(value = "联系人姓名", required = true)
            @RequestParam
                    String linkname,


            @ApiParam(value = "联系手机", required = true)
            @RequestParam
                    String linkphone,


            @ApiParam(value = "收货地址", required = true)
            @RequestParam
                    String linkaddress,


            @ApiParam(value = "买家留言", required = true)
            @RequestParam
                    String usermemo,


            @ApiParam(value = "订单备注", required = true)
            @RequestParam
                    String ordermemo,


            @ApiParam(value = "宝贝数量", required = true)
            @RequestParam
                    BigDecimal goodnum,


            @ApiParam(value = "修改后的收货地址", required = true)
            @RequestParam
                    String newaddress,


            @ApiParam(value = "0 未支付 1 微信 2 余额 3 线下", required = true)
            @RequestParam
                    Integer paytype,


            @ApiParam(value = "1 = 安装 2= 维修", required = true)
            @RequestParam
                    Integer ordertype,


            @ApiParam(value = "后台分配时间", required = true)
            @RequestParam
                    Date fpTime,


            @ApiParam(value = "工人确认时间", required = true)
            @RequestParam
                    Date confirmTime,


            @ApiParam(value = "订单状态 -1 =已删除 0 = 待分配 1=已分配待确认 2 已确认待完成 3=已完成", required = true)
            @RequestParam
                    Integer status,

            @ApiParam(value = "选填参数控制 默认不填", hidden = true)
            @RequestParam(required = false)
                    Integer extra) {
        CourierorderModel courierorder = new CourierorderModel();

        courierorder.setUserid(userid);


        courierorder.setUsername(username);


        courierorder.setLinkname(linkname);


        courierorder.setLinkphone(linkphone);


        courierorder.setLinkaddress(linkaddress);


        courierorder.setUsermemo(usermemo);


        courierorder.setOrdermemo(ordermemo);


        courierorder.setGoodnum(goodnum);


        courierorder.setNewaddress(newaddress);


        courierorder.setPaytype(paytype);


        courierorder.setOrdertype(ordertype);


        courierorder.setFpTime(fpTime);


        courierorder.setConfirmTime(confirmTime);


        courierorder.setStatus(status);


        courierorderService.create(courierorder);
        return new AppBack();

    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @ResponseBody
    @RequiresRole(role = "1")
    @ApiOperation(
            value = "更新",
            notes = "备注：",
            httpMethod = "POST")
    public AppBack update(@ApiParam(value = "用户ID")
                          @RequestParam(required = false)
                                  Integer userid,
                          @ApiParam(value = "买家会员名")
                          @RequestParam(required = false)
                                  String username,
                          @ApiParam(value = "联系人姓名")
                          @RequestParam(required = false)
                                  String linkname,
                          @ApiParam(value = "联系手机")
                          @RequestParam(required = false)
                                  String linkphone,
                          @ApiParam(value = "收货地址")
                          @RequestParam(required = false)
                                  String linkaddress,
                          @ApiParam(value = "买家留言")
                          @RequestParam(required = false)
                                  String usermemo,
                          @ApiParam(value = "订单备注")
                          @RequestParam(required = false)
                                  String ordermemo,
                          @ApiParam(value = "宝贝数量")
                          @RequestParam(required = false)
                                  BigDecimal goodnum,
                          @ApiParam(value = "修改后的收货地址")
                          @RequestParam(required = false)
                                  String newaddress,
                          @ApiParam(value = "0 未支付 1 微信 2 余额 3 线下")
                          @RequestParam(required = false)
                                  Integer paytype,
                          @ApiParam(value = "1 = 安装 2= 维修")
                          @RequestParam(required = false)
                                  Integer ordertype,
                          @ApiParam(value = "后台分配时间")
                          @RequestParam(required = false)
                                  Date fpTime,
                          @ApiParam(value = "工人确认时间")
                          @RequestParam(required = false)
                                  Date confirmTime,
                          @ApiParam(value = "订单状态 -1 =已删除 0 = 待分配 1=已分配待确认 2 已确认待完成 3=已完成")
                          @RequestParam(required = false)
                                  Integer status,
                          @ApiParam(value = "的ID", required = true)
                          @RequestParam int courierorderId) {
        CourierorderModel courierorder = new CourierorderModel();
        courierorder.setUserid(userid);
        courierorder.setUsername(username);
        courierorder.setLinkname(linkname);
        courierorder.setLinkphone(linkphone);
        courierorder.setLinkaddress(linkaddress);
        courierorder.setUsermemo(usermemo);
        courierorder.setOrdermemo(ordermemo);
        courierorder.setGoodnum(goodnum);
        courierorder.setNewaddress(newaddress);
        courierorder.setPaytype(paytype);
        courierorder.setOrdertype(ordertype);
        courierorder.setFpTime(fpTime);
        courierorder.setConfirmTime(confirmTime);
        courierorder.setStatus(status);
        courierorder.setId(courierorderId);

        courierorderService.update(courierorder);
        return new AppBack();
    }
    /**
     * 获取工人信息
     */
    @RequestMapping("/getOrderCourier")
    @ResponseBody
    @RequiresRole(role = "0")
    @ApiOperation(
            value = "后台专用",
            httpMethod = "POST"
    )
    public  AppBack getOrderCourier(Integer id){
        CourierModel courierModel = courierService.getById(id);
        if ((courierModel == null)) {
            return new AppBack(-1, "资源不存在");

        }else{
            return new AppBack(courierModel);
        }

    }

    /**
     * 工人订单操作 status 0 = 接单  -1 =拒绝接单
     */
    @RequestMapping("/confirmOrder")
    @ResponseBody
//    @RequiresRole(role = "0")
    @ApiOperation(
            value = "工人操作订单",
            notes = "备注:",
            httpMethod = "POST"
    )
    public  AppBack confirmOrder(@ApiParam(value = "订单id",required = true)
                                 @RequestParam Integer courierorderId,
                                 @ApiParam(value = "订单操作0=接单,-1=拒绝接单 1=完成订单",required = true)
                                 @RequestParam int status,
                                 @ApiParam(value = "验证码",required = true)
                                     @RequestParam String code,
                                 @ApiParam(value = "图片",required = true)
                                     @RequestParam String pics
                                 ){
        CourierorderModel courierorderModel = courierorderService.getById(courierorderId);
        if (courierorderModel == null){
            return new AppBack(-1, "资源不存在");
        }
        if (status == 0){
            courierorderModel.setStatus(2);
            courierorderModel.setConfirmTime(new Date());
            courierorderService.update(courierorderModel);

        }
        if (status==-1){

            courierorderModel.setStatus(0);
            courierorderModel.setCourierid(0);
            courierorderService.update(courierorderModel);
        }
        if (status == 1){
            Map condition = new HashMap();
//            condition.put("phone", phone);
            condition.put("code", code);
            List<UserVerifyModel> verifyList = userVerifyService.getListLite(condition);
            if (verifyList.size() == 0) {
                return new AppBack(-2, "验证码错误");
            }
            else {
                String[] imgs = pics.split(",");
                for (String photo :imgs){
                    if (photo != ""){
                        OrderpicModel orderpicModel = new OrderpicModel();
                        orderpicModel.setOrderid(courierorderId);
                        orderpicModel.setPic(photo);
                        orderpicModel.setOrdertype(1);
                        orderpicService.create(orderpicModel);

                    }
                }

                courierorderModel.setStatus(3);
                courierorderModel.setEnd_time(new Date());
                courierorderService.update(courierorderModel);


            }

        }
        return  new AppBack();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @ResponseBody
    @RequiresRole(role = "1")
    @ApiOperation(
            value = "删除",
            notes = "备注：",
            httpMethod = "POST")
    public AppBack delete(@ApiParam(value = "的ID", required = true)
                          @RequestParam
                                  int courierorderId) {

        CourierorderModel newCourierorder = new CourierorderModel();
        newCourierorder.setStatus(-10);
        newCourierorder.setId(courierorderId);
        courierorderService.update(newCourierorder);
        return new AppBack();
    }



}
